package GameDemo.FightState;

import GameDemo.FightState.AllState.*;
import GameDemo.Actor;
import java.util.ArrayList;
import java.util.Collections;


//一般大多数buff管理自己的状态，
// BaseMutexState类型的状态，由FightStateMgr会引用管理
public class FightStateMgr {
    private ArrayList<MutexStateMgr> mutexStates = new ArrayList<>(StateMutexType.MaxNum.ordinal()); //BaseMutexState对象保存在别的系统，这里引用一份管理那个生效
    ArrayList<BaseFightState> stateList = new ArrayList<>(); //不归buff管理的其他状态,比如一个技能效果，产生1秒后掉血的状态
    Actor owner;
    // * //同施法者才互斥
    // * HashMap<Integer, HashMap<Integer, MutexStateMgr>> m_stateMgrs ;//施法者id, 互斥id, state

    public FightStateMgr(Actor owner) {
        this.owner = owner;
        for (int i = 0; i < StateMutexType.MaxNum.ordinal(); i++) {
            mutexStates.add(new MutexStateMgr());
        }
    }

    public void AddState(BaseFightState state) {
        stateList.add(state);
    }

    public void RemoveState(BaseFightState obj) {
        // 交换后删除
        int lastIndex = stateList.size() - 1;
        for (int i = 0; i <= lastIndex; i++) {
            if (stateList.get(i) == obj) {  // 根据对象引用直接比较（非 equals）
                Collections.swap(stateList, i, lastIndex); // 交换到末尾
                stateList.remove(lastIndex); // 删除末尾元素
                return;
            }
        }
    }

    public void AddMutexState(BaseMutexState state) {
        mutexStates.get(state.GetMutexType().ordinal()).Add(state);
    }

    public void RemoveMutexState(BaseMutexState state) {
        mutexStates.get(state.GetMutexType().ordinal()).Remove(state);
    }
    
}

class MutexStateMgr {
    private ArrayList<BaseMutexState> states = new ArrayList<>(StateMutexType.MaxNum.ordinal());
    private BaseMutexState curActiveState = null;
    
    public MutexStateMgr() {
    }

    public void Add(BaseMutexState state) {   
        states.add(state);
        if (null == curActiveState) {
            curActiveState = state;
        }
        else
        {
            if (state.Priority() > curActiveState.Priority()) {
                curActiveState.OnDeactivate();
                curActiveState = state;
                curActiveState.OnActivate();
            }
        }
    }

    public void Remove(BaseMutexState state) {
        states.remove(state);
        if (state == curActiveState) {
            curActiveState.OnDeactivate();
        }

        curActiveState = GetMaxPriState();
        if (curActiveState != null) {
            curActiveState.OnActivate();
        }
    }

    ////////////////////////////private/////////////////
    private BaseMutexState GetMaxPriState() {
        BaseMutexState maxPriState = null;
        for (BaseMutexState state : states) {
            if (maxPriState == null || state.Priority() > maxPriState.Priority()) {
                maxPriState = state;
            }
        }
        return maxPriState;
    }
   
}